package br.gov.cemaden.library.repository.observacao;

import br.gov.cemaden.library.model.alerta.Aerodromo;
import br.gov.cemaden.library.model.observacao.Metar;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

/**
 *
 * @author alan
 */
public class MetarRepository {

    private final EntityManager em;
    
    public MetarRepository(EntityManager em){
        this.em = em;
    }
    
    public Metar persist(Metar metar){
        em.getTransaction().begin();
        em.persist(metar);
        em.getTransaction().commit();
        return metar;
    }
    
    public Metar find(Date date, Aerodromo aerodromo){
        try{
            Metar m = em.createQuery("SELECT m FROM Metar m WHERE m.atualizacao = :atualizacao AND m.aerodromo = :aerodromo", Metar.class)
                    .setParameter("atualizacao", date)
                    .setParameter("aerodromo", aerodromo)
                    .getSingleResult();
            
            return m;
        }
        catch(NoResultException ex){
            return null;
        }
    }
    
}
